<template>
  <div class="page-modal">
    <el-dialog
      destroy-on-close
      v-model="dialogVisible"
      title="新建用户"
      width="30%"
      center
    >
      <HyForm v-model="formData" v-bind="modalConfig"></HyForm>
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from "vue";
import { useStore } from "vuex";

import HyForm from "@/base-ui/form";
export default defineComponent({
  // 6:30 - 9:30 吃完饭半小时到10:30
  props: {
    modalConfig: {
      type: Object,
      required: true,
    },
    defaultInfo: {
      type: Object,
      default: () => ({}),
    },
    pageName: {
      type: String,
      required: true,
    },
    otherInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    HyForm,
  },
  setup(props) {
    // 新建框formDate 数据
    const formData = ref<any>({});
    const dialogVisible = ref(false);

    watch(
      () => props.defaultInfo,
      (newValue) => {
        for (const item of props.modalConfig.formItems) {
          formData.value[`${item.field}`] = newValue[`${item.field}`];
        }
      }
    );

    // 点击确认按钮
    const store = useStore();
    const handleConfirmClick = () => {
      dialogVisible.value = false;
      // 判断是否为空 新建用户是个空对象，编辑就是实际对象
      if (Object.keys(props.defaultInfo).length) {
        // 编辑
        console.log("编辑用户");
        store.dispatch("systemModule/editPageDataAction", {
          pageName: props.pageName,
          editData: { ...formData.value, ...props.otherInfo },
          id: props.defaultInfo.id,
        });
      } else {
        // 新建
        console.log("新建用户");
        store.dispatch("systemModule/createPageDataAction", {
          pageName: props.pageName,
          newData: { ...formData.value, ...props.otherInfo },
        });
      }
    };
    return {
      dialogVisible,
      formData,
      handleConfirmClick,
    };
  },
});
</script>
<style scoped></style>
